/**
 * 视频管理service
 */
(function(window, angular, undefined){
	var VideoControlService = angular.module('VideoControlService', ['ui.router','itfreer','waterCommon']);
	
	VideoControlService.service('$VideoService',
		function($itfreerHttp,$itfreer,$waterDataCommon,$httpData,$state,$queryObj){
		// 获取通道
	  	function getChannelInfo(szIP,iw) {
	  		WebVideoCtrl.I_GetAnalogChannelInfo(szIP, {
	  			async: false,
	  			success: function (xmlDoc) {
	  				var oChannels = $(xmlDoc).find("VideoInputChannel");
	  				nAnalogChannel = oChannels.length;
	  				var id=0;
	  				$.each(oChannels, function (i) {
	  					var id = parseInt($(this).find("id").eq(0).text(), 10),
	  						name = $(this).find("name").eq(0).text();
	  					if ("" == name) {
	  						name = "Camera " + (id < 9 ? "0" + id : id);
	  					}
	  					
	  				});
	  				console.log(szIP + " 获取模拟通道成功！");
	  				clickStartRealPlay(szIP,iw,id);
	  			},
	  			error: function () {
	  				console.log(szIP + " 获取模拟通道失败！");
	  			}
	  		});
	  	}
	 // 开始预览
	  	function clickStartRealPlay(szIP,g_iWndIndex,iChannelID) {
	  		var oWndInfo = WebVideoCtrl.I_GetWindowStatus(g_iWndIndex),
	  			iStreamType = parseInt("1", 10),
	  			iChannelID = parseInt("1", 10),
	  			bZeroChannel = false;
	  		console.log(szIP+" "+g_iWndIndex);
	  		if ("" == szIP) {
	  			return;
	  		}

	  		if (oWndInfo != null) {// 已经在播放了，先停止
	  			WebVideoCtrl.I_Stop();
	  		}

	  		var iRet = WebVideoCtrl.I_StartRealPlay(szIP, {
	  			iWndIndex: g_iWndIndex,
	  			iStreamType: iStreamType,
	  			iChannelID: iChannelID,
	  			bZeroChannel: bZeroChannel
	  		});

	  		if (0 == iRet) {
	  			console.log( szIP+" 开始预览成功");
	  		} else {
	  			console.log( szIP+" 开始预览失败");
	  		}
	  	}
	  //注册
	  	this.clickLogin=function (szIP,szPort,szUsername,szPassword,iw) {
	  		var sstr=WebVideoCtrl.I_Logout(szIP);
	  		var iRet = WebVideoCtrl.I_Login(szIP, 1, szPort, szUsername, szPassword, {
	  			async: false,
	  			success: function (xmlDoc) {
	  				setTimeout(function () {
	  					getChannelInfo(szIP,iw);
	  				}, 10);
	  				console.log(szIP + " 登录成功！");
	  			},
	  			error: function () {
	  				console.log(szIP + " 登录失败！");
	  			}
	  		});

	  		if (-1 == iRet) {
	  			console.log(szIP + " 已登录过！");
	  			setTimeout(function () {
  					getChannelInfo(szIP,iw);
  				}, 10);
	  		}
	  	}
		
		});
}(window, angular));